package com.atguigu.orderService.controller;


import com.atguigu.commonUtils.JwtUtils;
import com.atguigu.commonUtils.Result;
import com.atguigu.commonUtils.ResultEnum;
import com.atguigu.commonUtils.ResultUtil;
import com.atguigu.orderService.entity.Order;
import com.atguigu.orderService.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author Chen Wen bo
 * @since 2021-08-20
 */
@Api(tags = "订单模块")
@RestController
@RequestMapping("/orderService/order")
@CrossOrigin
public class OrderController {

    @Resource
    private OrderService orderService;

    @ApiOperation("创建订单")
    @PostMapping("/createOrder/{courseId}")
    public Result<Map<String,String>> createOrder(@PathVariable String courseId, HttpServletRequest request) {
        Map<String,String> map = new HashMap<>();
        String id = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(id)) {
            return ResultUtil.defineSuccess(ResultEnum.INVALID_TOKEN.code,null,"用户已失效");
        }
        String orderId = orderService.createOrder(courseId, id);
        map.put("orderId",orderId);
        return ResultUtil.success(map);
    }


    @ApiOperation("根据订单号查询订单信息")
    @GetMapping("/getOrderInfo/{orderId}")
    public Result<Order> getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no",orderId);
        Order order = orderService.getOne(orderQueryWrapper);
        return ResultUtil.success(order);
    }

    @ApiOperation("根据课程ID和用户ID查询订单表中的订单状态")
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public Result<Boolean> isBuyCourse(@PathVariable String courseId, @PathVariable String memberId) {
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("course_id",courseId);
        orderQueryWrapper.eq("member_id",memberId);
        orderQueryWrapper.eq("status",1);
        int count = orderService.count(orderQueryWrapper);
        return ResultUtil.success(count>0);
    }

}

